<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span> 总的数据:{{ total }}条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" size="small" type="success" @click="importExcel">导入excel</el-button>
          <el-button v-allow="'export_excel'" size="small" type="warning" @click="exportToExcel">导出excel</el-button>
          <el-button v-allow="'add'" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{ prop: 'timeOfEntry', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!-- 添加显示用户的头像 -->
          <el-table-column label="头像">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="width: 100%;"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 方式一：查询参数 -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <!-- 方式二：路径参数 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>-
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 7, 9, 11]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" :close-on-click-modal="false" :close-on-press-escape="false" @close="hClose">
        <addOrEdit ref="myEmp" @success="hSuccess" />
      </el-dialog>

      <!-- 分配角色的弹层 -->
      <el-dialog title="分配角色" :visible.sync="assignShowDialog" :close-on-click-modal="false" :close-on-press-escape="false">
        <assignRole v-if="assignShowDialog" :user-id="userId" @close="assignShowDialog=false" />
      </el-dialog>

      <!-- 生成二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import qrCode from 'qrcode'
import addOrEdit from './empDialog.vue'
import assignRole from './assignRole.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
// reduce完成这个功能
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  name: 'Employees',
  components: {
    addOrEdit,
    assignRole
  },
  data() {
    return {
      showCodeDialog: false,
      assignShowDialog: false, // 控制分配角色弹层的显示和隐藏
      showDialog: false,
      list: [],
      total: 0,
      page: 1, // 页码
      size: 5, // 每页显示条数
      userId: ''
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          qrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.error('请上传图片')
      }
    },
    hAssignRole(id) {
      this.userId = id
      this.assignShowDialog = true
    },
    importExcel() {
      this.$router.push('/import')
    },
    exportToExcel() {
      // 1.发生请求获取需要导出的数据
      // 页面渲染的时候已经发送请求将数据保存到th1s,L1st中
      // 2.将数据格式成excel需要的格式
      const { tHeader, result } = this.formatToExcel(this.list)
      // console.log(tHeader, 'tHeader')
      // console.log(results, 'results')
      // 3.调用admin提供的函数将数据写入到excel
      import('@/vendor/Export2Excel').then(excel => {
        // 2. 格式化数据
        // export_json_to_excel将格式化的数据写入到excel
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '', // 设置文件的名称  ''
          autoWidth: true, // 宽度自适应   true
          bookType: 'xlsx' // 导入的文件类型  'xlsx'
        })
      })
    },
    formatToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
      // 1 生成表头
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(en_key => {
        return mapInfo[en_key]
      })
      // 2 生成表的内容data
      const result = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, result }
    },
    // 删除
    async hDel(id) {
      this.$confirm('您确定删除吗？').then(async() => {
        const res = await delEmployee(id)
        // console.log(res)
        // 当前页只有一条数据的时候
        if (this.list.length === 1) {
        // 页码减一，往前跳一页
          this.page--
          // 页码小于等于0的时候
          if (this.page <= 0) {
          // 把页码定死在第一页，不页码继续减
            this.page = 1
          }
        }
        // 用状态吗判断是否删除成功
        if (res.code === 10000) {
        // 删除成功就更新数据
          this.loadEmployeesList()
        }
      }).catch(error => console.log(error))
    },
    // 重置表单
    hClose() {
      // 重置表单
      this.$refs.myEmp.resetForm()
    },
    // 子传父触发
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      // 新增成功，关闭弹层
      this.showDialog = false
      // 重新刷新页面
      this.loadEmployeesList()
    },
    // 格式化聘用形式的数据
    formatHireType(value) {
      // value的值有可能是1 || 2
      // const obj = employeesEnum.hireType.find(item => item.id === value)
      // return obj ? obj.value : '未知'
      return hireType[value] || '未知'
    },
    // 获取员工列表
    async loadEmployeesList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        // console.log(res, 'loadEmployeesList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 当前显示的条数进行切换时触发---val每页的条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeesList()
    },
    // 当前的页码值进行切换时触发---val---当前的页码值
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    }
  }
}
</script>
